import { Request, Response } from "express";
import UserModel from "../schema/user";
import { getToken } from "../utils/jwt";

import Common from "./common";
const UserCommonIns = new Common(UserModel);

import ResType from "./resType";
const ResTypeIns = new ResType();

import { get } from "../http/http";
import Types from "../typings";

class System {
  constructor() {}

  async login(req: Request, res: Response) {
    try {
      const { account, password } = req.body;

      const users = await UserCommonIns.Find({ account, password });

      if (!users.length) {
        ResTypeIns.isNotExist(res);
      } else {
        const user = users[0];

        // 加密对象
        const payload = {
          id: user.id,
          account: user.account,
          password: user.password,
          name: user.name,
          roleId: user.roleId,
          gender: user.gender,
          avatar: user.avatar,
          desc: user.desc,
          createdTime: user.createdTime,
          updatedTime: user.updatedTime,
          creator: user.creator,
        };

        // 获取 token
        const token = await getToken(payload);

        // 将 token 设置为 cookie
        res.cookie("token", token, {
          // httpOnly: true,
          maxAge: 1000 * 60 * 60 * 24, // 1 天过期
        });

        ResTypeIns.Success(res, { ...payload, token });
      }
    } catch (err) {
      ResTypeIns.Database(res, err);
    }
  }

  async todoInfo(req: Request, res: Response) {
    const params = { page: 1, size: 999999 };
    const job = get(req, "/api/job/list", params);
    const development = get(req, "/api/development/list", params);
    const life = get(req, "/api/life/list", params);

    const resolves = await Promise.all([job, development, life]);
    const jobData = resolves[0] as { list: Types.Job.JobType[] };
    const developmentData = resolves[1] as {
      list: Types.Development.DevelopmentType[];
    };
    const lifeData = resolves[2] as { list: Types.Life.LifeType[] };

    ResTypeIns.Success(res, {
      job: jobData.list,
      development: developmentData.list,
      life: lifeData.list,
    });
  }
}

export default System;
